package com.tgy.springmvc.interceptor;

import com.tgy.springmvc.constant.WebMvcConstant;
import com.tgy.springmvc.util.RequestUtil;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.FlashMapManager;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author: tgy
 * @Date: 2020-08-24 09:42
 */
public class LoginHandlerInterceptor implements HandlerInterceptor  {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Object session = RequestUtil.getSession(WebMvcConstant.SESSION_USER_KEY);

        if (Objects.isNull(session)){

            response.sendRedirect("/to-login");

//            FlashMap flashMap = new FlashMap();
//
//            flashMap.put("redirectUrl",request.getRequestURI());
//            FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);
//
//            flashMapManager.saveOutputFlashMap(flashMap,request,response);
            RequestUtil.setSession(WebMvcConstant.REDIRECT_URL_KEY, request.getRequestURI());
            return false;
        }

        request.setAttribute("user",session);

        return true;
    }
}
